<template>
  <Container>
    <div slot="header" class="container-header title title-center">{{ info.couponName }}
      <Button size="large" class="fl btn-back" icon="ios-arrow-back" @click="$router.go(-1)">返回</Button>
    </div>
    <div class="bg-light mt">
      <div class="container-title">基本信息</div>
      <Form :label-width="130">
        <Row>
          <i-col span="8">
            <FormItem label="优惠券类别：">{{ couponDiscountTypeMap[info.couponDiscountType] }}</FormItem>
            <FormItem label="促销类型：">{{ couponPromotionTypeMap[info.couponPromotionType] }}</FormItem>
            <FormItem label="使用期限：">{{ info.date }}</FormItem>
            <FormItem v-show="info.couponPromotionType !== 'FULL_COUPON_ACTIVE_COUPON' && info.receiveStartDate && info.receiveEndDate" label="领取日期：">{{ `${info.receiveStartDate} - ${info.receiveEndDate}` }}</FormItem>
            <FormItem label="设置：">{{ info.couponStatus == 'OPEN' ? '启用' : '未启用' }}</FormItem>
            <FormItem label="发放渠道：">{{ info.couponSendChannelEnum | SendChannelFilter }}</FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="优惠券名称：">{{ info.couponName }}</FormItem>
            <FormItem label="优惠券类型：">{{ info.couponType === 'COUPON_PLATFORM' ? '工厂券' : '商品券' }}</FormItem>
            <FormItem v-show="info.couponDiscountType !== 'DISCOUNT_COUPON'" label="优惠券面额：">{{ info.denomination }}</FormItem>
            <FormItem label="发行量：">{{ info.amount === -1 ? '不限' : info.amount }}</FormItem>
            <FormItem label="优惠券说明：">{{ info.remark }}</FormItem>
            <FormItem v-if="info.couponDiscountType === 'DENOMINATION_COUPON' && info.useQuantityPerProduct" label="每个商品能用：">{{ info.useQuantityPerProduct }}张</FormItem>
            <FormItem label="优惠券使用类型：">{{ info.couponUseQuantityTypeEnum | couponUseFilter }}</FormItem>
          </i-col>
          <i-col span="8">
            <FormItem v-show="info.couponDiscountType !== 'CASH_COUPON'" label="使用条件：">{{ info.couponDiscountType == 'DISCOUNT_COUPON' ? handleDiscountCouponUseCondition(info.discountGroupList) : info.useCondition }}</FormItem>
            <FormItem label="推广方式：">{{ info.receiveMethod === "SELLER_SEND" ? '卖家发放' : '买家领取' }}</FormItem>
            <FormItem label="限领：">{{ info.receiveLimitType === 'LIMIT_NONE' ? '不限制' : info.receiveLimitType === "LIMIT_ONE" ? `每人限领${info.receiveLimitQuantity}张` : `每人每天限领${info.receiveLimitQuantity}张` }}</FormItem>
            <FormItem label="是否公开：">{{ info.isPublic ? '是' : '否' }}</FormItem>
            <FormItem v-if="info.couponDiscountType === 'DENOMINATION_COUPON'" label="使用权重：">{{ info.weights }}</FormItem>
          </i-col>
        </Row>
      </Form>
      <Loader :status="detailStatus" @refresh="getData" />
    </div>
    <!-- 搜寻条件 -->
    <div v-if="detailStatus==='pass'" class="bg-light">
      <div v-if="info.couponType !== 'COUPON_PLATFORM'" class="container-header mt">
        <Form class="search">
          <Row>
            <i-col span="6">
              <FormItem label="店铺类目">
                <ShopSelect v-model="list.form.ownerCategoryId" @input="getProductData(tabIndex)" />
              <!-- <treeselect v-model="list.form.categoryId" :options="categoryList" placeholder="请选择分类"/> -->
              </FormItem>
            </i-col>
            <i-col span="6">
              <FormItem label="商品品牌">
                <Select v-model="list.form.brandId" clearable @on-change="getProductData(tabIndex)">
                  <Option
                    v-for="item in brandList"
                    :key="item.id"
                    :value="item.brandId"
                  >
                    {{ item.text }}
                  </Option>
                </Select>
              </FormItem>
            </i-col>
            <i-col span="5">
              <FormItem label="商品名称">
                <Input v-model="list.form.keyword" :maxlength="100" placeholder="请输入商品名称" @on-enter="getProductData(tabIndex)" />
              </FormItem>
            </i-col>
            <i-col span="5">
              <FormItem label="商品编码">
                <Input v-model="list.form.code" :maxlength="30" placeholder="请输入商品编码" @on-enter="getProductData(tabIndex)" />
              </FormItem>
            </i-col>
            <i-col span="2" class-name="search small">
              <Button class="btn-search" type="primary" icon="ios-search" @click="getProductData(tabIndex)" />
            </i-col>
          </Row>
        </Form>
      </div>
      <Tabs v-if="info.couponType !== 'COUPON_PLATFORM' && info.couponDiscountType === 'DENOMINATION_COUPON'" value="tab1">
        <TabPane name="tab1" label="活动商品">
          <Table
            stripe
            :columns="list.columns"
            :height="options.tableHeight"
            :data="list.data"
            no-data-text="亲，没有找到相关记录哦！~"
          />
          <div class="pager">
            <Page
              :total="list.totalItem"
              :current="list.currentPage"
              :page-size="list.pageSize"
              show-sizer
              placement="top"
              @on-change="onSelectedPageChange"
              @on-page-size-change="onSelectedPageSizeChange"
            />
          </div>
          <Loader :status="list.status" @refresh="getData" />
        </TabPane>
      </Tabs>
      <Tabs v-if="info.couponType !== 'COUPON_PLATFORM' && info.couponDiscountType === 'DISCOUNT_COUPON'" v-model="discountTab" @on-click="changeTab">
        <TabPane v-for="(item, index) in info.discountGroupList" :key="index" :label="item.group+'阶:'+item.discount+'折商品'" :name="'discountTab'+index">
          <Table
            stripe
            :columns="list.columns"
            :height="options.tableHeight"
            :data="discountGroupData[index]"
            no-data-text="亲，没有找到相关记录哦！~"
          />
          <div class="pager">
            <Page
              :total="list.discountPage[index].totalItem"
              :current="list.discountPage[index].currentPage"
              :page-size="list.discountPage[index].pageSize"
              show-sizer
              placement="top"
              @on-change="onDiscountPageChange(index, $event)"
              @on-page-size-change="onDiscountPageSizeChange(index, $event)"
            />
          </div>
          <Loader :status="list.discountPage[index].status" @refresh="getData(item.group)" />
        </TabPane>
      </Tabs>
    </div>
  </Container>
</template>
<script>
import { formatCurrency } from '@/util'
import ShopSelect from '@/components/ShopSelect'
import listData from './CouponDetailData'
import { mapGetters } from 'vuex'
export default {
  components: {
    ShopSelect
  },
  filters: {
    couponUseFilter (v) {
      let list = {
        'NONE_LIMIT': '不限',
        'PRODUCT_LIMIT': '限商品',
        'LIMIT_ONE': '每单限1张'
      }
      return list[v]
    },
    SendChannelFilter (v) {
      let list = {
        'NONE_LIMIT': '不限',
        'TIRE_INSURANCE': '轮胎保小程序',
        'CLOUD_APP': '中策云店',
        'SALESMAN': '业务通'
      }
      return list[v]
    }
  },
  data () {
    return {
      id: this.$route.query.id || null,
      detailStatus: 'pass',
      list: listData,
      options: {
        tableHeight: 300
      },
      //优惠券类别
      couponDiscountTypeMap: {
        DENOMINATION_COUPON: '满减券',
        DISCOUNT_COUPON: '折扣券',
        CASH_COUPON: '现金券'
      },
      //促销类型
      couponPromotionTypeMap: {
        FACTORY_ACTIVE_COUPON: '工厂促销券',
        FULL_COUPON_ACTIVE_COUPON: '满额返券促销券',
        GENERAL_COUPON: '普通券'
      },
      info: {
        couponSendChannelEnum: '',
        date: '', //使用期限
        amount: null,
        couponName: '',
        couponStatus: '',
        couponType: '', // 添加
        couponPromotionType: '',
        couponDiscountType: '', //优惠券类别
        denomination: '',
        isPublic: '',
        receiveBackUrl: '', // 返回链接可为空
        receiveEndDate: '',
        receiveLimit: '',
        weights: '',
        receiveMethod: '',
        receiveStartDate: '',
        remark: '',
        useCondition: '',
        receiveLimitQuantity: '',
        discountGroupList: [],
        receiveLimitType: '',
        couponUseQuantityTypeEnum: '',
        useQuantityPerProduct: null
      },
      discountTab: 'discountTab0',
      discountGroupData: { 0: [], 1: [], 2: [], 3: [], 4: [] },
      tabIndex: 1
    }
  },
  computed: {
    ...mapGetters(['rankList', 'brandList', 'categoryList'])
  },
  mounted () {
    this.$store.dispatch('getBrandList')
    this.$store.dispatch('getCategoryList')
    // this.$store.dispatch('getRankList', true).then(() => {
    //   if (this.id) this.getData()
    // })
    if (this.id) this.getData()
  },
  methods: {
    onSelectedPageChange (number) {
      this.list.currentPage = number
      this.getProductData()
    },
    onSelectedPageSizeChange (pageSize) {
      this.list.pageSize = pageSize
      this.getProductData()
    },
    onDiscountPageChange (index, number) {
      this.list.discountPage[index].currentPage = number
      this.getProductData(this.tabIndex)
    },
    onDiscountPageSizeChange (index, pageSize) {
      this.list.discountPage[index].pageSize = pageSize
      this.getProductData(this.tabIndex)
    },
    changeTab (name) {
      this.resetSearch()
      this.tabIndex = Number(name[11]) + 1
      this.getProductData(this.tabIndex)
    },
    resetSearch () {
      this.list.form.brandId = null
      this.list.form.ownerCategoryId = null
      this.list.form.keyword = null
      this.list.form.code = null
    },
    getProductData (groups = 1) {
      let param = {
        couponId: this.id,
        brandId: this.list.form.brandId,
        ownerCategoryId: this.list.form.ownerCategoryId,
        keyword: this.list.form.keyword,
        code: this.list.form.code,
        groups: groups
      }
      if (this.info.couponDiscountType === 'DENOMINATION_COUPON') {
        this.list.status = 'loading'
        param.current = this.list.currentPage
        param.size = this.list.pageSize
      } else {
        this.list.discountPage[groups - 1].status = 'loading'
        param.current = this.list.discountPage[groups - 1].currentPage
        param.size = this.list.discountPage[groups - 1].pageSize
      }

      this.$ajaxGet('/coupon/coupon_info/product/spu_page', param).then(data => {
        if (this.info.couponDiscountType === 'DENOMINATION_COUPON') { //满减券
          this.list.data = data.records || []
          this.list.totalItem = Number(data.total)
          this.list.status = 'pass'
        } else { //折扣券
          this.list.discountPage[groups - 1].totalItem = Number(data.total)
          this.discountGroupData[groups - 1] = data.records || []
          this.list.discountPage[groups - 1].status = 'pass'
        }
      }).catch(() => {
        if (this.info.couponDiscountType === 'DENOMINATION_COUPON') { //满减券
          this.list.status = 'error'
        } else { //折扣券
          this.list.discountPage[groups - 1].status = 'error'
        }
      })
    },
    getData (groups = 1) {
      this.detailStatus = 'loading'
      this.list.status = 'loading'
      this.list.discountPage[groups - 1].status = 'loading'
      this.$ajaxGet(`/coupon/coupon_info/detail/${this.id}`).then(data => {
        this.detailStatus = 'pass'
        Object.keys(this.info).forEach(key => {
          if (key === 'date') {
            this.info.date = data.validityType === 'RELATIVE_TIME' ? data.validityDays + '天' : (data.validityStartDate + ' - ' + data.validityEndDate)
          } else if (key === 'denomination' || key === 'useCondition') {
            this.info[key] = formatCurrency(data[key], true)
          } else {
            this.info[key] = data[key]
          }
        })
        if (this.info.couponType !== 'COUPON_PLATFORM') {
          let param = {
            couponId: this.id,
            brandId: this.list.form.brandId,
            ownerCategoryId: this.list.form.ownerCategoryId,
            keyword: this.list.form.keyword,
            code: this.list.form.code,
            groups: groups
          }
          if (this.info.couponDiscountType === 'DENOMINATION_COUPON') {
            param.current = this.list.currentPage
            param.size = this.list.pageSize
          } else {
            param.current = this.list.discountPage[groups - 1].currentPage
            param.size = this.list.discountPage[groups - 1].pageSize
          }
          this.$ajaxGet('/coupon/coupon_info/product/spu_page', param).then(data => {
            if (this.info.couponDiscountType === 'DENOMINATION_COUPON') { //满减券
              this.list.status = 'pass'
              this.list.data = data.records || []
              this.list.totalItem = Number(data.total)
            } else { //折扣券
              this.list.discountPage[groups - 1].totalItem = Number(data.total)
              this.discountGroupData[groups - 1] = data.records || []
              this.list.discountPage[groups - 1].status = 'pass'
            }
          })
        }
      }).catch(() => {
        this.detailStatus = 'error'
      })
    },
    handleDiscountCouponUseCondition (discountGroupList) {
      const length = discountGroupList.length
      if (length === 1) {
        return `${discountGroupList[0].discount}折`
      } else {
        return `${discountGroupList[0].discount} - ${discountGroupList[length - 1].discount}折`
      }
    }
  }
}
</script>

